/**
 * @description 此组件为面积图
 * @example
 * {idName： bar,
 *  xAxis: ['星期一', '星期二'],
 *  data: [
 *  {label: 'legend1', value:[{key: '星期一', value: 20},{key: '星期二', value: 20}]},
 * {label: 'legend2', value:[{key: '星期一', value: 20},{key: '星期二', value: 20}]}，
 * ]
 * }
 * @author muisuidaan
 */

import React, { useEffect,forwardRef,useImperativeHandle } from "react";
import { downloadImg } from '@/utils/echarts'

import * as echarts from "echarts";
import {
  axisLabelStyle,
  axisLineStyle,
  splitLineStyle,
  TOOLTIP_FONT_SIZE,
  yaxisLabelStyle,
  yaxisLineStyle,
} from "@/utils/echarts";
import * as _ from 'lodash'
import useIoObserve from '@/hook/useIoObserve'
import numeral from "numeral";

interface VProps {
  key: string; // 与x轴对应的值
  value: number; // y轴对应的值
  title?:string;
}

export interface DataProps {
  label: string; // legend对应的中文
  value: VProps[];
  yAxisIndex?:number;//左右轴
}

export interface AreaProps {
  idName: string; // 每一个echarts图需要一个dom来创建实例，该id用来标识唯一dom
  xAxis: string[]; // x轴为字符串数组
  legend: string[];
  data: DataProps[];
  color?: string[];
  percent?:boolean;
  showLine?:boolean;//是否带线
  notShowArea?:boolean;//不展示面积
  notShowStack?:boolean;//是否堆叠-默认是
  smooth?:boolean;//是否平滑
  print?:boolean;//是否需要打印
  legendStyle?:object;
  gridStyle?:object;
  stickToBottom?:boolean;//是否贴底
  numFixed?:string;
  addType?:string;//面积图单条补充前后数据类型 day天/month月/year年
  notNeedSort?:boolean;//不需要对面积图的tooltip进行倒叙操作-默认需要进行倒序，不需要倒序notNeedSort置为true
}

const Area = forwardRef((props: AreaProps, ref: any) => {
  const { idName, xAxis, data, legend, color,percent,notShowArea,showLine,smooth,print,legendStyle,gridStyle,notShowStack,stickToBottom,numFixed,addType="day",notNeedSort} = props;
  console.log('Area-props',props);

  let newData = [];
  let newXAxis = [];
  if(xAxis?.length===1 && !notShowArea){
    // const prev = moment(xAxis[0]).subtract(1, 'day').format('YYYY-MM-DD');
    // const next= moment(xAxis[0]).add(1, 'day').format('YYYY-MM-DD')
    const prev = 'a';
    const next= 'b';
    newData = data.map((item=>{
      return {
        ...item,
        value:[
          {key:prev,value:item?.value?.length>0?item.value[0]?.value:0},
          item.value[0],
          {key:next,value:item?.value?.length>0?item.value[0]?.value:0},

        ]

      }
    }))
    newXAxis = [prev,...xAxis,next];
  }
  
  const handleAreaData = (arr: any, str?: string) => {
    console.log('arr',arr)
    let res: any = [];
    arr.map((v) => {
      res.push([v.key, v.value]);
    });
    console.log('res****************',res, str);
    return res;
  };
  const getyAxisMinMax = (start?: number, end?: number) => {
    let min = 1000000,
      max = -100000
    data.map((v) => {
      v.value.forEach((m) => {
        min = min > m.value ? m.value : min
        max = max < m.value ? m.value : max
      })
    })
    return {
      min: min,
      max: max,
    }
  }
  

  const options = {
    // animation: false,
    color,
    tooltip: {
      show:true,
      trigger: "axis",
      // trigger: "item",
      zIndex: 2,
      backgroundColor: "rgba(65,69,81,0.96)",
      extraCssText: "border-radius:2px;padding:6px 10px",
      borderRaduis:20,
      borderWidth: 0,
      textStyle: {
        fontSize: TOOLTIP_FONT_SIZE,
        color: "#fff",
        lineHeight:'28px'
      },
      enterable:true,
      
      formatter: (params)=> {
        // console.log('params',params,params[0].axisValue,params[0].axisValue=='a')
        let htmlStr = '<div class="echarts_tooltip"><p style="margin:0">' + (!notShowArea && xAxis?.length === 1?xAxis[0]:params[0].axisValue) + '</p>';
       if(!notShowArea && !notShowStack && !notNeedSort){
         //如果是面积图且是堆积图
        for (let i = params.length-1; i >-1; i--) {
          htmlStr += `<div ><p style="margin-right:8px" title="${params[i]?.seriesName}">${params[i]?.marker +params[i]?.seriesName}</p><p class="value">${ numFixed?numeral(params[i].value[1]).format(numFixed):params[i].value[1]}${percent?"%":""}</p></div>`
          // '<p >' +params[i]?.marker +params[i]?.seriesName + ':' +params[i]?.value[1] + '</p>';
          // total +=params[i].value[1];
        }
        

       }else{
         //不需要做倒序处理
          for (let i = 0; i < params.length; i++) {
            htmlStr += `<div ><p style="margin-right:8px" title="${params[i]?.seriesName}">${params[i]?.marker +params[i]?.seriesName}</p><p class="value">${ numFixed?numeral(params[i]?.value[1]).format(numFixed):(params[i]?.value[1]||params[i]?.value[1]===0?params[i]?.value[1]:'-')}${percent?"%":""}</p></div>`
            // '<p >' +params[i]?.marker +params[i]?.seriesName + ':' +params[i]?.value[1] + '</p>';
            // total +=params[i].value[1];
          }

          
       }

       
        // htmlStr += `<p>${total}</p>`
        htmlStr += '</div>'
        return htmlStr
      },
      position: (point, params, dom, rect, size)=> {
        // 提示框 限制在chart 图中
        let x = 0; // x坐标位置
        let y = 0; // y坐标位置

        let pointX = point[0];
        let pointY = point[1];

        // 提示框大小
        let boxWidth = size.contentSize[0];
        let boxHeight = size.contentSize[1];

        // boxWidth > pointX 说明鼠标左边放不下提示框
        if (boxWidth > pointX +20) {
          x = pointX + 25;
        } else {
          // 左边放的下
          x = pointX - boxWidth -20;
        }

        if (boxHeight > pointY+10) {
          y =pointY + 10;
        } else {
          // 上边放得下
          y = pointY - boxHeight -20;
        }
        // console.log([x, y])
        // dom.style.transform = 'translateZ(0)'  // 提示框被遮挡时可以设置
        return [x, y];
      },
      confine: true
    },
    xAxis: {
      type: "category",
      data: newXAxis?.length>0?newXAxis:xAxis,
      boundaryGap: false,
      axisLabel: {
        ...axisLabelStyle(),
        fontSize: 8,
        // 使用字符串模板，模板变量为刻度默认标签 {value}
        formatter: (value, index)=> {
          // console.log('value',value)
          // console.log('index',index)
          if(xAxis?.length===1 && !notShowArea && index!=1)return '';
          return value ;
      }

      },
      axisTick: {
        show: false,
        alignWithLabel: true,
      },
      axisLine: {
        ...axisLineStyle(),
        show: true,
      },
      splitLine: {
        show: false,
      },
     ...( smooth?splitLineStyle():{}),
    },
    yAxis: [
      {
        type: "value",
        position:"left",
        splitNumber: 5,
        axisTick: {
          show: false,
          alignWithLabel: true,
        },
        ...yaxisLineStyle(),
        axisLine: {
          ...yaxisLineStyle(),
          show: true,
        },
        axisLabel: {
          ...yaxisLabelStyle(),
          inside: false,
          fontSize: 8,
          formatter: percent?'{value} %':'{value}'
        },
        max:notShowArea?null:100,
        min:stickToBottom?(value)=> {
          return value.min;//是否贴底
        }:null,
        alignTicks: true,
        ...splitLineStyle(),
        
      },
      {
        type: "value",
        position:"right",
        splitNumber: 5,
        axisTick: {
          show: false,
          alignWithLabel: true,
        },
        ...yaxisLineStyle(),
        axisLine: {
          ...yaxisLineStyle(),
          show: true,
        },
        axisLabel: {
          ...yaxisLabelStyle(),
          inside: false,
          fontSize: 8,
          formatter: percent?'{value} %':'{value}'
        },
        max:notShowArea?null:100,
        min:smooth?(value)=> {
          return Math.floor(value.min);
        }:null,
        alignTicks: true,
        ...splitLineStyle(),
      }
    ],
    grid: {
      left: 10,
      right: 40,
      bottom: 10,
      top: 40,
      containLabel: true,
      ...gridStyle
    },
    legend: {
      left:"center",
      type:print?"plain":"scroll",
      data: legend,
      icon: "rectangle",
      itemWidth: 11,
      itemHeight: 11,
      itemGap:  print?5:20,
      top: -6,
      textStyle: print?{
        fontSize: 10,
        color: '#35425e',
        // width: 48,
        height: 28,
        lineHeight: 28,
        padding: [0, 0, -3, 2],
        maxWidth: 30,
        overflow: 'truncate',
        ellipsis: '...',
      }:{
        fontSize: 10,
        color: '#35425e',
        width: 48,
        height: 28,
        lineHeight: 28,
        padding: [0, 0, -3, 2],
      },
      ...legendStyle
    },
    series: (newData?.length>0?newData:data).map((v) => {
      // console.log(handleAreaData(v.value), v.label, legend,);
      return {
        name: v.label,
        data: handleAreaData(v.value),
        type: "line",
        top: "22%",
        stack:notShowStack?undefined: "Total",
        // areaStyle: notShowArea?null:{
        //   opacity:showLine?0.3:0.6
        // },
        areaStyle: notShowArea?null:{
          opacity:showLine?0.4:0.6
        },
        lineStyle:{
          width:showLine?1:0
          // width:1

        },
        connectNulls: true,
        emphasis: notShowArea?{
          focus: "series",
          lineStyle: {
            width: 2,
          },
        }:{
          focus: "none",
          // borderWidth: 2,
          // areaStyle: {
          //   opacity: 0.2,
          // },
          // disabled:true
        },
        symbol: 'none',
        smooth,
        yAxisIndex:v?.yAxisIndex
        // triggerLineEvent: true,//是否响应和触发鼠标事件，默认不响应。

      };
    }),
  };

  useImperativeHandle(ref, () => ({
    downloadImg: (title: string) => {
      options.legend.textStyle.width = undefined
      downloadImg(title, options);
    },
  }));
  const handleGenBar = () => {
    const arr = []
    data.map(v => {
      if (!arr.includes(v.axisType)) {
        arr.push(v.axisType)
      }
    })
    
    const chartDom = document.getElementById(`${idName}`);
    if (chartDom) {
      const w = parseFloat(getComputedStyle(chartDom).width)
      // console.log(legend);
      const fontWidth = legend.join('')?.length * 11 // 假设每个字占12px时， 所有字需要的宽度
      const minLength = (w - 40 - legend.length * 12 - (legend.length - 1) * 12)
      let legendW = 0
      if (fontWidth > minLength) {
        legendW = (w - 40 - legend.length * 12 - (legend.length - 1) * 12) / legend.length
        options.legend.textStyle.width = legendW ? Number(legendW) : 48
      }
      const myChart = echarts.init(chartDom);

      // if (arr.includes(1)) {
      //   options.yAxis[0].splitLine.show = true
      // }
      // if (arr.length < 2) {
      //   options.yAxis[1].splitLine.show = true
      // }
     
      myChart.setOption(options);
       // 注册 mouseover 事件，类目轴名称切换为自定义颜色
      // myChart.on('mouseover', params => {
      //   console.log('params',params)

      //   if (params.componentType === 'yAxis') {//进入y轴文字回调
      //     // 获取鼠标当前在那一块数据上，对数据进行特殊处理
      //     const yAxisName = params.value;
      //   }
      // })
      return myChart
    }/*  */
  };

  // 窗口大小改变
  const handleChangeSize = () => {
    setTimeout(() => {
      const dom = document.getElementById(idName);
      dom?.removeAttribute("_echarts_instance_");
      handleGenBar();
    }, 1);
  };

   useIoObserve(null, handleChangeSize, idName)

  useEffect(() => {
    // console.log('data',data);
    handleGenBar();
    window.addEventListener("resize",  handleChangeSize);
    return () => {
      const dom = document.getElementById(idName);
      dom?.removeAttribute("_echarts_instance_");
      window.removeEventListener("resize", handleChangeSize);
    };
  }, [data]);
  // console.log("options",options)
  return <div id={idName} style={{ width: "100%", height: "100%" }} onClick={(e)=>{e.stopPropagation()}}></div>;
});

export default Area;
